from typing import Dict
import jinja2 as jj2
import pathlib
from .Template import Template
from .Content import get_content
from functools import singledispatch
from . import global_vars
from . import markdown2

g_current_path = pathlib.Path(__file__).parent.absolute()


def tag_loader(tag):
    return fr'<{tag}>{{{{childred}}}}</{tag}>'


class Report:

    cls_main_template_path = './template/main.html'
    cls_main_css_path = './template/main.css'

    def __init__(self, template_base_path='.') -> None:
        self.inputs = []
        self.srcs=[]
        self.has_alt=False
        self.template_base_path = template_base_path

        self.main_template = Template._create_by_libs_env(
            Report.cls_main_template_path)
        css_tl = Template._create_by_libs_env(Report.cls_main_css_path)
        self.main_template.set_var(
            'css_style', f'<style>{css_tl.render()}</style>')

        self.tag_env = jj2.Environment(loader=jj2.FunctionLoader(tag_loader))
        self.components_env = global_vars.create_jj2_env_components()

    def add_template(self, template: Template):
        self.inputs.append(template)
        return self

    def add_template_detail(self, name, **kws):
        tl = Template(name)
        tl.set_vars(**kws)
        self.add_template(tl)
        return self

    def add_tag(self, tag: str, *contents):
        pass
        tl = Template(tag, self.tag_env)
        tl.set_var('childred', contents)

        return self

    def add_title(self, content):
        tl = Template('title.html', self.components_env)
        tl.set_var('content', content)
        self.add_template(tl)
        return self

    def add_div(self, content):
        tl = Template('div.html', self.components_env)
        content = get_content(content,self) or content
        tl.set_var('content', content)
        self.add_template(tl)
        return self

    def add_row(self, *contents):
        tl = Template('row_div.html', self.components_env)
        contents = (
            get_content(c,self) or c
            for c in contents
        )
        tl.set_var('childred', contents)
        self.add_template(tl)
        return self

    def add_md(self,content:str):
        self.add_template(markdown2.markdown(content))
        return self

    def _add_scripts(self,*srcs):
        self.srcs.extend(srcs)
        return self

    def to_html(self, file: str):
        if self.has_alt:
            self._add_scripts('https://cdn.jsdelivr.net/npm//vega@5','https://cdn.jsdelivr.net/npm//vega-lite@4.8.1','https://cdn.jsdelivr.net/npm//vega-embed@6')

        self.main_template.set_var('templates', self.inputs)
        self.main_template.set_var('scripts',self.srcs)
        self.main_template.to_file(pathlib.Path(file))
